import Icon from '@/components/Icon';
import NavBar from '@/components/NavBar';
import { useAppSelector } from '@/store';
import {
  clearHistoriesAction,
  clearSuggestsAction,
  getSuggestsAction,
  saveHistoriesAction,
} from '@/store/action/search';
import { useEffect, useRef, useState } from 'react';
import { useDispatch } from 'react-redux';
import styles from './index.module.scss';
import DOMPurify from 'dompurify';
import { Toast } from 'antd-mobile';
import { removeLocalHistories, setLocalHistories } from '@/utils/storage';
import { useHistory } from 'react-router-dom';

const highlight = (keyword: string, item: string) => {
  const reg = new RegExp(`(${keyword})`, 'gi');
  return item.replace(reg, `<span onclick="alert(123)" >$1</span>`);
};

export default function Search() {
  const timerIdRef = useRef(-1);
  const dispatch = useDispatch();
  const history = useHistory();

  const [keyword, setKeyword] = useState('');

  useEffect(() => {
    if (!keyword) {
      dispatch(clearSuggestsAction());
    }
  }, [keyword, dispatch]);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setKeyword(e.target.value);
    clearTimeout(timerIdRef.current);
    if (!e.target.value.trim()) return;
    timerIdRef.current = window.setTimeout(() => {
      dispatch(getSuggestsAction(e.target.value));
    }, 500);
  };

  useEffect(() => {
    return () => {
      clearTimeout(timerIdRef.current);
      dispatch(clearSuggestsAction());
    };
  }, [dispatch]);

  const { suggestList, histories } = useAppSelector((state) => state.search);

  useEffect(() => {
    setLocalHistories(histories);
  }, [histories]);

  const handleClear = () => {
    setKeyword('');
    dispatch(clearSuggestsAction());
  };

  const handleSearch = () => {
    if (!keyword.trim()) return Toast.show({ content: '搜索内容不能为空' });
    handleGotoResult(keyword);
    dispatch(saveHistoriesAction(keyword));
  };

  const handleClearHistores = () => {
    dispatch(clearHistoriesAction());
    removeLocalHistories();
  };

  const handleGotoResult = (key: string) => {
    // 1. state传参
    // 2. 动态路由
    // 3. 拼接查询字符串
    history.push('/search/result?q=' + key);
  };

  const tenHistories = histories.slice(0, 10);

  return (
    <div className={styles.root}>
      <NavBar
        right={
          <span className="search-text" onClick={handleSearch}>
            搜索
          </span>
        }
      >
        <div className="navbar-search">
          <Icon type="iconbtn_search" className="icon-search" />

          <div className="input-wrapper">
            <input
              type="text"
              placeholder="请输入关键字搜索"
              value={keyword}
              onChange={(e) => handleChange(e)}
              onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
            />

            {!!keyword.trim() && (
              <Icon type="iconbtn_tag_close" className="icon-close" onClick={handleClear} />
            )}
          </div>
        </div>
      </NavBar>

      {!keyword.trim() && !!histories.length && (
        <div className="history" style={{ display: 'block' }}>
          <div className="history-header">
            <span>搜索历史</span>
            <span onClick={handleClearHistores}>
              <Icon type="iconbtn_del" />
              清除全部
            </span>
          </div>

          <div className="history-list">
            {tenHistories.map((item) => {
              return (
                <span className="history-item" key={item} onClick={() => handleGotoResult(item)}>
                  {item}
                  <span className="divider"></span>
                </span>
              );
            })}
          </div>
        </div>
      )}

      <div className="search-result">
        {suggestList.map((item, index) => {
          return (
            <div className="result-item" key={index} onClick={() => handleGotoResult(item)}>
              <Icon className="icon-search" type="iconbtn_search" />
              <div
                className="result-value"
                dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(highlight(keyword, item)) }}
              ></div>
            </div>
          );
        })}
      </div>
    </div>
  );
}
